/*
 * change different short numbers and show the number in a formatted way during typing
 *
 * 1e -> 1.000
 * 1m -> 1.000.000
 */

(function($){
	$.fn.easynumber = function(options){
		
		var settings = $.extend({
			hundred			: 'h',
			thousand			: 't',
			million			: 'm',

			decimals			:	2,		//number of deciamls
			dec_point		: '.',	//decimals' separator
			thousands_sep	: ',',	//thousands separator

			textalign		:	'right'	//align text in input
			}, options );
		
		var decimals = 0;
		
		var $input = this;
		if(!$input.is(":input")){
			console.log('easynumber should be called for an input element');
			return;
		}
		
		$(function(){
			$input.css('text-align', 'right');
		})
		
		$input.bind('input.easynumber', function(){
			var num = $input.val();
			
			if (num.substr(0,1) == settings.dec_point) {		//if it starts ith decial point change it to 0.
				num = '0' + num;
			}
			if(isNaN(parseInt(num))) {
				console.log('The given value is not a number');
			}
			else{		//we got something like a number
				decimals = 0;
				num = num.split(settings.thousands_sep).join('');		//cut out thousands separators

				//shortcuts
				if (num.search(settings.million) != -1) {
					num = num.replace(settings.million, '000000');
				}
				if (num.search(settings.thousand) != -1) {
					num = num.replace(settings.thousand, '000');
				}
				if (num.search(settings.hundred) != -1) {
					num = num.replace(settings.hundred, '00');
				}
				
				//decimals
				var dPos = num.search(settings.dec_point);	//decimal point position in the number
				if (dPos >= 0) {
					decimals = settings.decimals;
					if (dPos == (num.length - 1)) {		//the user added a decimal point
						num = num.substr(0, num.length - 1);		//cut down deimal point
					}
					else if (dPos < num.length - 1) {		//5214,005
						var n = num.split(settings.dec_point);
						var decimalPart = n[1].replace(/0/g, '');
						num = n[0] + '.' + decimalPart;
					}
				}

			}
			$input.val(number_format(num));
		});
		
		function number_format(number){
			var prefix = number < 0 ? "-" : "",
				i = parseInt(number = Math.abs(+number || 0).toFixed(decimals)) + "",
				j = (j = i.length) > 3 ? j % 3 : 0;
			return prefix + (j ? i.substr(0, j) + settings.thousands_sep : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + settings.thousands_sep) + (decimals ? settings.dec_point + Math.abs(number - i).toFixed(decimals).slice(2) : "");
		}
		
		return this;	//required for chaining
	}
}(jQuery));